package com.gjintel.framework.user.dao.impl;

import com.gjintel.framework.dict.model.Dictionary;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.user.dao.IUserDao;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.model.UserGoodsType;
import com.gjintel.framework.user.model.UserRight;
import com.gjintel.framework.user.model.UserRole;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.sdk.base.dao.HibernateGenericDAO;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.StringUtil;
import org.activiti.engine.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import com.gjintel.framework.goodstype.model.GoodsType;
/**
 * @description 用户数据访问实现
 * @author fengya
 * @date 2015-7-31 下午01:13:35
 */
@Repository("userDao")
public class UserDaoImpl extends HibernateGenericDAO implements IUserDao {

	@Autowired
	private IdentityService identityService;

	@SuppressWarnings("unchecked")
	public List<User> findAll(Page page, User user, Sort sort,
			int loginUserType, String loginUserDeptUnit,String roles) {
		StringBuffer hql = new StringBuffer(
				" from User u where u.flag=0 and u.id!='1' and u.registerId is null");
		List<String> params = new ArrayList<String>(2);
//		if (loginUserType == 0) {
//			hql.append(" and exists(select 1 from Dept d where d.pUnit=? and d.id=u.deptId) ");
//			params.add(loginUserDeptUnit);
//		}

		if (user != null) {
			if (!StringUtil.isEmpty(user.getName())) {
				hql.append(" and u.name like ? ");
				params.add("%" + user.getName() + "%");
			}
			if (!StringUtil.isEmpty(user.getLoginName())) {
				hql.append(" and u.loginName like ? ");
				params.add("%" + user.getLoginName() + "%");
			}

			if (!StringUtil.isEmpty(user.getRoleName())) {
				hql.append(" and EXISTS(select 1 from UserRole ur where ur.roleId=? and ur.userId=u.id) ");
				params.add(user.getRoleName());
			}
			if (!StringUtil.isEmpty(user.getDeptId())) {
				hql.append(" and u.deptId = ?");
				params.add(user.getDeptId());
			}
			
			if(!StringUtil.isEmpty(roles)){
				hql.append(" and u.id in(select ur.userId from UserRole ur where ur.roleId=?)");
				params.add(roles);
			}
		}

		return this.findAsPage(hql.toString(), page, sort, "u", true,
				params.toArray());
	}

	@SuppressWarnings("unchecked")
	public List<UserRole> getUserRole(String roleId) {
		return this.find("from UserRole ur where ur.roleId=?", roleId);
	}

	@SuppressWarnings("unchecked")
	public List<Role> getUserRoles(String userId) {
		return this
				.find("from Role r where exists(select 1 from UserRole ur where ur.userId=? and ur.roleId = r.id)",
						userId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void roleUsers(Page page, String roleId, Sort sort, boolean roleUser) {
		String hql = null;
		if (roleUser) {
			hql = "from User u where exists(select 1 from UserRole ur where ur.roleId=? and ur.userId=u.id)";
		} else {
			hql = "from User u where not exists(select 1 from UserRole ur where ur.roleId=? and ur.userId=u.id)";
		}
		// this.findAsPage(hql, page, sort, "u", true ,roleId);
		this.findAsPage(hql, page, sort, "u", roleId, true);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> login(String loginName) {
		return this.find("from User u where u.loginName=?", loginName);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUserByCompany(String company) {
		return this.find("from User u where u.companyName=?", company);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		return this.find("from User u where u.flag=0");
	}

	@Override
	public void getUsers(Page page, String userType, Sort sort) {
		StringBuilder hql = new StringBuilder("from User u where u.flag=0");
		if (!StringUtils.isEmpty(userType)) {
			hql.append(" and u.type=? ");
		}
		// this.findAsPage(hql.toString(), page, sort, "u", true, userType);
		this.findAsPage(hql.toString(), page, sort, "u", userType, true);
	}

	@Override
	public void removeUserRole(String userId) {
		String hql = "DELETE FROM UserRole ur WHERE userId = '" + userId + "'";
		this.executeUpdate(hql);
	}

	@Override
	public void removeUserRight(String userId) {
		String hql = "DELETE FROM UserRight ur WHERE userId = '" + userId + "'";
		this.executeUpdate(hql);

	}

	@Override
	public void removeGoodsType(String userId) {
		String hql = "DELETE FROM UserGoodsType ugt WHERE userId = '" + userId
				+ "'";
		this.executeUpdate(hql);
	}

	@Override
	public void saveUserRole(User user, String userId, String roleIds) {
		for (String roleId : roleIds.split(",")) {
			UserRole ur = new UserRole();
			ur.setUserId(userId);
			ur.setRoleId(roleId);
			ur.setCreaterId(user.getId());
			ur.setCreaterName(user.getName());
			ur.setCreateTime(new Date());
			this.saveOrUpdate(ur);
			addMembershipToIdentify(ur);
		}
	}

	public void addMembershipToIdentify(UserRole ur) {
		String roleId = ur.getRoleId();
		String userId = ur.getUserId();
		String groupId;
		groupId = CommUtil.getGroupId(roleId);

		org.activiti.engine.identity.User activitiUser=identityService.createUserQuery().userId(userId).singleResult();
		if(activitiUser==null){
			activitiUser = identityService.newUser(userId);
			identityService.saveUser(activitiUser);
		}

		identityService.deleteMembership(userId, groupId);
		identityService.createMembership(userId, groupId);
	}

	@Override
	public void saveUserRight(String userId, String rightVal) {
		for (String right : rightVal.split(",")) {
			UserRight ur = new UserRight();
			ur.setUserId(userId);
			ur.setRightValue(right);
			this.saveOrUpdate(ur);
		}
	}

	@Override
	public void saveUserGoodsType(String userId, String goodsTypeIds) {
		for (String goodsTypeId : goodsTypeIds.split(",")) {
			UserGoodsType ugt = new UserGoodsType();
			ugt.setUserId(userId);
			ugt.setGoodsTypeId(goodsTypeId);
			ugt.setCreateTime(new Date());
			this.saveOrUpdate(ugt);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Dictionary> getUserRights(String userId) {
		return this
				.find("from Dictionary d where exists(select 1 from UserRight ur where ur.userId=? and ur.rightValue = d.value)",
						userId);
	}

	// @Override
	// @SuppressWarnings("unchecked")
	// public List<GoodsType> getUserGoodsType(String userId) {
	// return
	// this.find("from GoodsType gt where exists(select 1 from UserGoodsType ugt where ugt.userId=? and ugt.goodsTypeId = gt.id)",
	// userId);
	// }

	@SuppressWarnings("unchecked")
	@Override
	public List<User> caLogin(String caName) {
		return this.find("from User u where u.caCard=? and u.flag != 1", caName);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getLoginUser(String loginName) {	
		return this.find("from User u where u.loginName=? and u.flag != 1", loginName);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getLoginUserByLoginName(String loginName) {
		return this.find("from User u where u.loginName=? and u.flag != 1", loginName);
	}

	@Override
	public User getUserByRegisterId(String registerId) {
		String hql = "from User u where u.registerId=? and u.flag != 1";
		List<Object> params = new ArrayList<Object>();
		params.add(registerId);
		return (User) this.findUnique(hql.toString(),params.toArray());
	}


}
